package com.beemans.common.app

import com.beemans.common.R
import com.beemans.common.ext.toString2
import com.blankj.utilcode.util.NetworkUtils
import com.google.gson.JsonParseException
import com.google.gson.JsonSyntaxException
import org.json.JSONException
import retrofit2.HttpException
import java.io.NotSerializableException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.text.ParseException
import javax.net.ssl.SSLHandshakeException

/**
 * @author tiamosu
 * @date 2021/3/12
 */
object ResponseErrorListenerImpl {
    private const val UNAUTHORIZED = 401
    private const val FORBIDDEN = 403
    private const val NOT_FOUND = 404
    private const val REQUEST_TIMEOUT = 408
    private const val INTERNAL_SERVER_ERROR = 500
    private const val BAD_GATEWAY = 502
    private const val SERVICE_UNAVAILABLE = 503
    private const val GATEWAY_TIMEOUT = 504

    fun parseError(t: Throwable?): String {
        return if (t is HttpException) {
            convertStatusCode(t)
        } else if (t is JsonSyntaxException
            || t is JSONException
            || t is JsonParseException
            || t is ParseException
            || t is NotSerializableException
        ) {
            R.string.common_net_request_failed.toString2()
        } else if (t is ClassCastException) {
            R.string.common_net_request_failed.toString2()
        } else if (t is ConnectException) {
            R.string.common_net_connect_failed.toString2()
        } else if (t is SocketTimeoutException) {
            R.string.common_net_request_timeout.toString2()
        } else if (t is SSLHandshakeException) {
            R.string.common_net_connect_failed.toString2()
        } else if (t is UnknownHostException) {
            R.string.common_net_connect_failed.toString2()
        } else if (t is NullPointerException) {
            R.string.common_net_request_failed.toString2()
        } else if (t is RuntimeException) {
            t.message ?: R.string.common_net_abnormal_operation.toString2()
        } else if (!NetworkUtils.isConnected()) {
            R.string.common_net_connect_failed.toString2()
        } else {
            R.string.common_net_request_failed.toString2()
        }
    }

    private fun convertStatusCode(httpException: HttpException): String {
        return when (httpException.code()) {
            UNAUTHORIZED, FORBIDDEN, NOT_FOUND, REQUEST_TIMEOUT, INTERNAL_SERVER_ERROR,
            BAD_GATEWAY, SERVICE_UNAVAILABLE, GATEWAY_TIMEOUT
            -> R.string.common_net_connect_service_timeout.toString2()
            else -> R.string.common_net_connect_service_timeout.toString2()
        }
    }
}